package com.sychip.fhc.app.wsn.nav


import androidx.annotation.StringRes
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.ManageHistory
import androidx.compose.material.icons.filled.Map
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.TableRows
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import androidx.navigation.NavOptions
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.fhc.base.BackHandler
import com.fhc.base.EventObserver
import com.fhc.base.EventType
import com.fhc.base.FhcFlowEventBus
import com.fhc.base.FlowEventBusData
import com.fhc.base.KeepScreenOn
import com.fhc.base.LocalManager.stringResource
import com.fhc.view.BottomBarBox
import com.fhc.view.GlobalLoadingView
import com.fhc.view.utils.ToastyShow
import com.infinum.snacky.SnackyAnimationSpec
import com.infinum.snacky.SnackyHost
import com.infinum.snacky.rememberSnackyHostState
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import com.sychip.fhc.AppCoverScreen
import com.sychip.fhc.IS_DEBUG
import com.sychip.fhc.MainApplication
import com.sychip.fhc.app.todo.R
import com.sychip.fhc.app.wsn.screen.WsnAboutScreen
import com.sychip.fhc.app.wsn.screen.WsnListScreen
import com.sychip.fhc.app.wsn.screen.WsnMapScreen
import com.sychip.fhc.app.wsn.screen.WsnRssiDetailScreen
import com.sychip.fhc.app.wsn.screen.WsnSettingsScreen
import com.sychip.fhc.app.wsn.screen.WsnTestHisScreen
import com.sychip.fhc.lib.base.navArguments
import com.sychip.fhc.lib.base.rememberKeyboardState
import com.sychip.fhc.lib.base.slideInRight
import com.sychip.fhc.lib.base.slideOutRight
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import timber.log.Timber


const val NAV_JSON_ARG = "navJsonArg"
data class PostToWsnDetail(val fromDevId: String,val toDevId: String, val fromTime: Long, val toTime: Long)
const val WsnScreen_Rssi_Detail = "WsnScreen_Rssi_Detail"
const val WsnScreen_TestHis_Detail = "WsnScreen_TestHis_Detail"
const val Wsn_Rssi_Detail_Route ="$WsnScreen_Rssi_Detail?${NAV_JSON_ARG}={$NAV_JSON_ARG}"

enum class WsnTabScreens {
    ScreenMap,
    ScreenList,
    ScreenTestHis,
    ScreenSetting,
    ScreenAbout
}
sealed class WsnNavigationItem(val route: String, @StringRes val label: Int, val icon: ImageVector) {
    data object NavItem_Map : WsnNavigationItem(
        WsnTabScreens.ScreenMap.name,
        R.string.wsn_tab_map,
        Icons.Default.Map
    )
    data object NavItem_List : WsnNavigationItem(
        WsnTabScreens.ScreenList.name,
        R.string.wsn_tab_list,
        Icons.Default.TableRows)

    data object NavItem_TestHis : WsnNavigationItem(
        WsnTabScreens.ScreenTestHis.name,
        R.string.wsn_tab_test_his,
        Icons.Default.ManageHistory)

    data object NavItem_Setting : WsnNavigationItem(
        WsnTabScreens.ScreenSetting.name,
        R.string.wsn_tab_setting,
        Icons.Default.Settings)

    data object NavItem_About : WsnNavigationItem(
        WsnTabScreens.ScreenAbout.name,
        R.string.wsn_tab_about,
        Icons.Default.Info)
}
val WsnTabItems = if (IS_DEBUG) listOf(
    WsnNavigationItem.NavItem_Map,
    WsnNavigationItem.NavItem_List,
//    WsnNavigationItem.NavItem_TestHis,
    WsnNavigationItem.NavItem_Setting,
    WsnNavigationItem.NavItem_About,
) else   listOf(
    WsnNavigationItem.NavItem_Map,
    WsnNavigationItem.NavItem_List,
    WsnNavigationItem.NavItem_Setting,
    WsnNavigationItem.NavItem_About,
)

class WsnTabNavigationActions(private val navController: NavHostController) {
    fun navigateToWsnListDetail(param: PostToWsnDetail? = null) {
        val moshi = Moshi.Builder()
            .add(KotlinJsonAdapterFactory())
            .build()
        val jsonAdapter = moshi.adapter(PostToWsnDetail::class.java).lenient()
        val json = jsonAdapter.toJson(param)

        var route = WsnScreen_Rssi_Detail
        if(param != null){
            route = "$route?${NAV_JSON_ARG}=$json"
        }

        //options 不起作用？？？
        val options: NavOptions = NavOptions.Builder()
            .setEnterAnim(R.anim.slide_in_right)
            .setExitAnim(R.anim.slide_out_left)
            .setPopEnterAnim(R.anim.slide_in_left)
            .setPopExitAnim(R.anim.slide_out_right)
            .build()
        navController.navigate( route = route, navOptions = options )
    }
    fun navigateToWsnTestHisDetail(param: PostToWsnDetail? = null) {
        val moshi = Moshi.Builder()
            .add(KotlinJsonAdapterFactory())
            .build()
        val jsonAdapter = moshi.adapter(PostToWsnDetail::class.java).lenient()
        val json = jsonAdapter.toJson(param)

        var route = WsnScreen_TestHis_Detail
        if(param != null){
            route = "$route?${NAV_JSON_ARG}=$json"
        }

        //options 不起作用？？？
        val options: NavOptions = NavOptions.Builder()
            .setEnterAnim(R.anim.slide_in_right)
            .setExitAnim(R.anim.slide_out_left)
            .setPopEnterAnim(R.anim.slide_in_left)
            .setPopExitAnim(R.anim.slide_out_right)
            .build()
        navController.navigate( route = route, navOptions = options )
    }
}

val WsnStartRoute = WsnNavigationItem.NavItem_Map.route
var currentRoute:String? = WsnStartRoute

@Composable
private  fun BottomNavigationBar(navController: NavController) {
    val navBackStackEntry by navController.currentBackStackEntryAsState()
    currentRoute = navBackStackEntry?.destination?.route


//    val modifier = Modifier.height(84.dp) // 自定义高度
    //小米手机，containerColor设置不起作用，模拟器时可以的；
//    containerColor = Color.DarkGray,
//    contentColor = Color.Black,
    val bottomBarBgColor = Color(0xFF0A0A0A)  //NavigationBarDefaults.containerColor
    NavigationBar( containerColor = bottomBarBgColor) {
        WsnTabItems.forEach { item ->
            NavigationBarItem(
                colors = NavigationBarItemDefaults.colors(
                    indicatorColor = colorScheme.onBackground.copy(alpha = 0.4f), // 设置选中背景
                    selectedIconColor = colorScheme.primary,
                    selectedTextColor = colorScheme.primary,
                    unselectedIconColor=colorScheme.onBackground.copy(alpha = 0.6f),
                    unselectedTextColor=colorScheme.onBackground.copy(alpha = 0.6f)
                ),
                icon = {
                    Icon( imageVector = item.icon,  contentDescription = null )
                },
                label = { Text (stringResource( item.label))},
                onClick = {
                    if(item.route != currentRoute) {
                        navController.navigate(item.route) {
                            // 切换TAB避免重新加载页面 关键配置：单例模式+状态恢复
                            launchSingleTop = true
                            restoreState = true
                            popUpTo(navController.graph.startDestinationId) {
                                saveState = true
                            }
                        }
                    }else{
                        currentRoute = item.route
                    }
                },
                selected = currentRoute == item.route,
            )
        }
    }
//    rememberSystemUiController().run {
//        setNavigationBarColor(bottomBarBgColor, false)
//    }
}



@OptIn(ExperimentalLayoutApi::class)
@Composable
fun WsnMainTabNavHost(
    modifier: Modifier = Modifier,
    navController: NavHostController = rememberNavController(),
    tabViewModel:WsnMainTabViewModel = hiltViewModel(),
    onBack: () -> Unit
) {
    MainApplication.instance().setWsnMainTabViewModel(tabViewModel)
    val isKeyboardOpen by rememberKeyboardState()
    val snackbarHostState = rememberSnackyHostState()
    val context = LocalContext.current
    tabViewModel.initUsbSerialManager(context)
    KeepScreenOn()
    val loadingState by tabViewModel.loadingState.collectAsStateWithLifecycle()
    val tabStateFlow by  tabViewModel.tabStateFlow.collectAsStateWithLifecycle()

    val firstInit by tabViewModel.firstInitFlow.collectAsStateWithLifecycle()
    val serialDataFlow by tabViewModel.serialDataFlow.collectAsStateWithLifecycle()

    GlobalLoadingView(loadingState) {
        Scaffold(
            snackbarHost = {
                SnackyHost(
                    hostState = snackbarHostState,
                    animationSpec = SnackyAnimationSpec(scaleFactor = 0.5f),
                )
            },
            modifier = modifier.fillMaxSize(),
            contentWindowInsets = WindowInsets(0, 0, 0, 0),
            topBar = {
            },
            bottomBar = {
                if(tabStateFlow.showBottomNavbar && !isKeyboardOpen)  BottomNavigationBar(navController)
            },
        ) { innerPadding ->
            val content = LocalContext.current
            BackHandler{ onBack() }
//            val usbFlow = tabViewModel.usbFlow.collectAsStateWithLifecycle()
//
//            if(usbFlow.value.isNew){
//                FhcAlertDialog(
//                    onDismissRequest = { tabViewModel.clearUsbData() },
//                    onConfirmation = {  tabViewModel.clearUsbData()}
//                )
//            }

            NavHost(
                navController = navController,
                startDestination = WsnStartRoute,
                modifier = Modifier.padding(innerPadding),
                enterTransition = { EnterTransition.None },  //不允许动画，避免tab切换闪烁
                exitTransition = { ExitTransition.None },
                popEnterTransition = { EnterTransition.None },
                popExitTransition = { ExitTransition.None },
                //.consumeWindowInsets(innerPadding)
            ) {
                composable(WsnNavigationItem.NavItem_Map.route) {
                    BackHandler(onBack = {
                        onBack()
                    })
                    Column {
                        // Filter 需要覆盖在屏幕最上，所以加Box
                        Box{
                            WsnMapScreen(navController = navController)
                        }
                    }
                }
                composable(WsnNavigationItem.NavItem_List.route) {
                    BackHandler(onBack = {
                        onBack()
                    })
                    Column {
                        WsnListScreen(navController = navController)
                    }
                }
                composable(WsnNavigationItem.NavItem_TestHis.route) {
                    BackHandler(onBack = {
                        onBack()
                    })
                    Column {
                        WsnTestHisScreen()
                    }
                }
                composable(WsnNavigationItem.NavItem_Setting.route) {
                    BackHandler(onBack = {
                        onBack()
                    })
                    Column {
                        WsnSettingsScreen()
                    }
                }
                composable(WsnNavigationItem.NavItem_About.route) {
                    BackHandler(onBack = {
                        onBack()
                    })
                    Column {
                        WsnAboutScreen()
                    }
                }
                composable(
                    Wsn_Rssi_Detail_Route,
                    arguments = listOf(
                        navArgument(NAV_JSON_ARG) { type = NavType.StringType; nullable = false },
                    ),
                    enterTransition = { slideInRight(content) },
                    exitTransition = { slideOutRight(content) },
                ) { entry ->
                    val (argObj, _) = entry.navArguments<PostToWsnDetail>()
                    val onBack: () -> Unit = {
                        navController.previousBackStackEntry?.let {
                            Timber.i("  WsnListDetailScreen:    %s  ", "来自 ${it.destination.route} 的返回  ")
                            navController.popBackStack()
                            CoroutineScope(Dispatchers.Main).launch {
//                            delay(600) // 与 XML 动画的 duration 保持一致
                                tabViewModel.showBottomNavbar(true)
                            }
                        }
                    }
                    BackHandler {
                        onBack()
                    }
                    Column(modifier = modifier) {
                        WsnRssiDetailScreen(
                            fromArgument = argObj,
                            onBack = onBack
                        )
                        BottomBarBox()
                    }
                }
            }

        }
        if(!serialDataFlow.isEmpty()){
            ToastyShow(serialDataFlow) {
//                tabViewModel.clearSerialData()
            }

        }
        if(firstInit){
            AppCoverScreen(){it->
                tabViewModel.firstInitFinished()
            }


            EventObserver(onCreate = {
                CoroutineScope(Dispatchers.Default).launch {
                    FhcFlowEventBus.subscribe<FlowEventBusData> { event->
                        CoroutineScope(Dispatchers.Main).launch {
                            if(event.dataType == EventType.UsbAttached){
                                tabViewModel.initUsbSerialManager(context)
                            }else if(event.dataType == EventType.UsbDetached){
                                tabViewModel.destoryUsbSerialManager()
                            }
                        }
                    }
                }
            })
        }
    }
}
